/**
 * 
 */
package org.o14x.alpha.ui.commands.newfile;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PlatformUI;
import org.o14x.alpha.ui.controller.UIController;
import org.o14x.alpha.util.Messages;

/**
 * New file command.
 * 
 * @author Olivier DANGREAUX
 */
public class NewFileCommand extends AbstractHandler {
	private UIController uiController;
	private static MessageFormat messageFormat = new MessageFormat(Messages.getString("NewFileCommand.file_creation_error_message")); //$NON-NLS-1$

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		// shows new file dialog
		showNewFileDialog(Messages.getString("NewFileCommand.new_file_name")); //$NON-NLS-1$

		return null;
	}

	/**
	 * Shows new directory dialog
	 * 
	 * @param initialName The intial name of the new file.
	 */
	private void showNewFileDialog(String initialName) {
		// current directory
		File currentDirectory = uiController.getDomain().getCurrentExplorerTab().getFolder();

		// dialog
		NewFileInputDialog newFileInputDialog = new NewFileInputDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), initialName, new NewFileInputValidator(currentDirectory));
		newFileInputDialog.setUiController(uiController);
		newFileInputDialog.open();

		// entered name
		String newFileName = newFileInputDialog.getValue();

		// try to create the file
		File newDirectory = new File(currentDirectory, newFileName);
		boolean fileCreated = false;
		try {
			fileCreated = newDirectory.createNewFile();
		} catch (IOException e) {

		}

		// chaeck if directory creation has succeeded
		if (!fileCreated) {
			MessageDialog.openWarning(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages.getString("NewFileCommand.file_creation_error"), messageFormat.format(new String[] { newFileName })); //$NON-NLS-1$
			showNewFileDialog(newFileName);
		} else {
			uiController.getUi().getFolderTreeView().update();
			uiController.getDomain().getCurrentExplorerTab().getFolderView().update();
		}
	}

	/**
	 * Returns the value of uiController.
	 *
	 * @return The value of uiController.
	 */
	public UIController getUiController() {
		return uiController;
	}

	/**
	 * Sets the value of uiController.
	 *
	 * @param uiController The value of uiController to set.
	 */
	public void setUiController(UIController uiController) {
		this.uiController = uiController;
	}
}
